from selenium.webdriver import Chrome
from lxml import etree
import time
import pymysql

'''

'''

if __name__ == '__main__':
    page = int(input("此页十五个数据，如果需要，请输入还需要几页："))

    pymysql_config = {
        'host': '127.0.0.1',
        'port': 3306,
        'user': 'root',
        'password': 'mysql',
        'database': 'phone',
        'charset': 'utf8'

    }

    # 建立连接
    conn = pymysql.connect(**pymysql_config)

    # 创建游标对象 查询的数据存在游标对象种
    cur = conn.cursor()

    # 建立浏览器
    chrome_obj = Chrome()

    chrome_obj.get('https://wap.zol.com.cn/list/57.html')
    if page == 0:
        print('一页的数据')
    else:
        for i in range(page):
            time.sleep(0.5)
            click_ = chrome_obj.find_element_by_xpath('//*[@id="J_LoadMore"]')
            click_.click()
            time.sleep(1)

    html_data = chrome_obj.page_source

    html_obj = etree.HTML(html_data)
    url = html_obj.xpath(
        "//ul[@class='product-list']//div[@class='fix-flex product-list__item']/a/@href")
    print(url)

    for i in range(len(url)):
        c = ''.join(url[i])
        d = 'https://wap.zol.com.cn/' + c
        print('手机具体网页的url：', d)
        time.sleep(0.5)

        chrome_obj.execute_script(f'window.open("{d}")')

        list_ = chrome_obj.window_handles
        chrome_obj.switch_to_window(list_[i + 1])

        html_data = chrome_obj.page_source
        html_obj = etree.HTML(html_data)
        # 手机名字
        title = html_obj.xpath("//div[@class='title']//text()")
        print(title)

        # 手机参数
        introduce = html_obj.xpath('//*[@id="_j_product_infos"]/a//text()')
        print(introduce)

        # 内存
        size = html_obj.xpath("/html/body/section[5]/ul/li[1]/a[1]//text()")
        print(size)

        # 价格
        price = html_obj.xpath("/html/body/section[5]/ul/li[1]/span/b//text()")
        print(price)

        # 内存2
        size2 = html_obj.xpath("/html/body/section[5]/ul/li[2]/a[1]//text()")
        print(size2)

        # 价格2
        price2 = html_obj.xpath(
            "/html/body/section[5]/ul/li[2]/span/b//text()")
        print(price2)
        time.sleep(1)

        # 入库Mysql
        cur.execute(
            'insert into b values (("%s"),("%s"), ("%s"), ("%s"), ("%s"), ("%s"))' %
            (title, introduce, size, price, size2, price2))
        conn.commit()
